package wykop.utils;

import java.util.List;

import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Created by IntelliJ IDEA. User: kad Date: 05.11.11 Time: 11:53 To change this
 * template use File | Settings | File Templates.
 */
public class XPathUtils {

	private final static org.apache.log4j.Logger logger = org.apache.log4j.Logger
			.getLogger("wykop.xml.xpath");

	private static XPathExpression compile(final String path) {
		try {
			return XPathFactory.newInstance().newXPath().compile(path);
		} catch (final XPathExpressionException e) {
			logger.info("An exception occurred while parsing xpath " + path, e);
			throw new RuntimeException(e);
		}
	}

	public static List<Node> extractNodes(final Node node, final String path) {
		final XPathExpression expression = compile(path);
		try {
			return XmlUtils.asList((NodeList) expression.evaluate(node,
					XPathConstants.NODESET));
		} catch (final XPathExpressionException e) {
			logger.info("An exception occurred while parsing xpath " + path, e);
			throw new RuntimeException(e);
		}
	}

	public static String extractString(final Node node, final String path) {
		final XPathExpression expression = compile(path);
		try {
			return (String) expression.evaluate(node, XPathConstants.STRING);
		} catch (final XPathExpressionException e) {
			logger.info("An exception occurred while parsing xpath " + path, e);
			throw new RuntimeException(e);
		}
	}

}
